<?php
require_once 'Zend/Db.php';
require_once 'Rol.class.php';

abstract class RolesProvider {

	public static function getRoles() {

		$registry = Zend_Registry :: getInstance();
		$config = $registry->config;

		$db = Zend_Db :: factory('Mysqli', array (
			'host' => $config->database->host,
			'username' => $config->database->username,
			'password' => $config->database->password,
			'dbname' => $config->database->name
		));
		$db->setFetchMode(Zend_Db :: FETCH_ASSOC);
		$sql = "SELECT R.ROL_ID AS ID, R.ROL_NOMBRE AS NOMBRE, RE.RESOURCE_NOMBRE AS RES_NOMBRE FROM ROL R INNER JOIN Rol_has_Resource RHR ON (RHR.ROL_ID = R.ROL_ID) INNER JOIN RESOURCE RE ON (RE.RESOURCE_ID = RHR.RESOURCE_ID) ORDER BY R.ROL_ID";
		$result = $db->fetchAll($sql);
		$ultimoId = $result[0]['ID'];
		$arrayRoles = array ();
		$rol = new Rol();
		$rol->setId($result[0]['ID']);
		$rol->setNombre($result[0]['NOMBRE']);
		foreach ($result as $row) {
			if ($ultimoId != $row['ID']) {
				$arrayRoles[] = $rol;
				$rol = new Rol();
				$rol->setId($row['ID']);
				$rol->setNombre($row['NOMBRE']);
				$ultimoId = $row['ID'];
			}
			$rol->add($row['RES_NOMBRE']);
		}
		$arrayRoles[] = $rol;
		return $arrayRoles;
	}

	public static function getRolesPairs() {
		$registry = Zend_Registry :: getInstance();
		$config = $registry->config;

		$db = Zend_Db :: factory('Mysqli', array (
			'host' => $config->database->host,
			'username' => $config->database->username,
			'password' => $config->database->password,
			'dbname' => $config->database->name
		));
		$db->setFetchMode(Zend_Db :: FETCH_OBJ);
		$result = $db->fetchPairs('SELECT ROL_ID AS ID, ' .
		'ROL_NOMBRE AS NOMBRE FROM ROL');
		return $result;

	}

	public static function saveRol($nombre, $arrayResourcesId) {

		$registry = Zend_Registry :: getInstance();
		$config = $registry->config;
		if (count($arrayResourcesId) == 0) {
			throw new Exception("No se puede agregar un rol si no se tienen recursos asociados a el.");
		}
		if ($nombre == "") {
			throw new Exception("El nombre del rol no puede estar vacio.");
		}
		$db = Zend_Db :: factory('Mysqli', array (
			'host' => $config->database->host,
			'username' => $config->database->username,
			'password' => $config->database->password,
			'dbname' => $config->database->name
		));
		$db->insert('ROL', array (
			'ROL_NOMBRE' => $nombre
		));
		$id = $db->lastInsertId();
		foreach ($arrayResourcesId as $resourceId) {
			$db->insert('Rol_has_Resource', array (
				'ROL_ID' => $id,
				'RESOURCE_ID' => $resourceId
			));
		}
	}
}
?>